package com.centaline.androidsalesblog.activities.mine;

import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.util.Base64;
import android.view.View;
import android.widget.ImageView;

import com.android.volley.VolleyError;
import com.bumptech.glide.BitmapTypeRequest;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.api.usercenter.UpdateUserImgApi;
import com.centaline.androidsalesblog.api.usercenter.UserInfoApi;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.events.UserOperate;
import com.centaline.androidsalesblog.model.databaseobject.UserDo;
import com.centaline.androidsalesblog.model.responseobject.UserCenterRo;
import com.centaline.androidsalesblog.model.responseobject.UserRo;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centanet.framework.glide.GlideLoad;
import com.centanet.framework.glide.RoundImageViewTarget;
import com.centanet.framework.interfaces.IResponseListener;
import com.centanet.framework.utils.ExternalCacheDirUtil;
import com.centanet.framework.utils.ImageUtil;
import com.trello.rxlifecycle.ActivityEvent;

import org.greenrobot.eventbus.EventBus;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Locale;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

/**
 * 我的资料
 * <p/>
 * Created by fusl1 on 2015/12/28.
 * Modify by Lihq on 2016/01/22.
 */
public class MyProfileActivity extends BaseActivity implements View.OnClickListener {

    private final String[] items = new String[]{"选择本地图片", "拍照"};

    public static final int SET_NICK_NAME = 1;
    private static final int SELECT_IMG = 2;
    private static final int SELECT_PHOTO = 3;

    private ImageView img_icon;//头像
    private AppCompatTextView atv_nickname;//昵称
    private AppCompatTextView atv_phone;//手机号

    private BitmapTypeRequest<String> mBitmapTypeRequest;
    private UpdateUserImgApi updateUserImgApi;
    private String picturePath;
    private String compressDir;//压缩保存目录

    @Override
    protected int setLayoutId() {
        return R.layout.activity_my_profile;
    }

    @Override
    protected void findViews() {
        setUniversalToolbar(R.string.title_my_profile);
        img_icon = (ImageView) findViewById(R.id.img_icon);
        atv_nickname = (AppCompatTextView) findViewById(R.id.atv_nickname);
        atv_phone = (AppCompatTextView) findViewById(R.id.atv_phone);
    }

    @Override
    protected void initViews() {
        mBitmapTypeRequest = GlideLoad.initRound(this);
        compressDir = ExternalCacheDirUtil.getImageCompressCacheDir(this);
        updateUserImgApi = new UpdateUserImgApi(MyProfileActivity.class, UserCenterRo.class, new IResponseListener<UserCenterRo>() {
            @Override
            public void onResponse(UserCenterRo userCenterRo) {
                if (userCenterRo.getResultNo() == 0) {
                    EventBus.getDefault().post(new UserOperate(1));
                    requestUserInfo();
                } else {
                    snack(userCenterRo.getRMessage());
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {
                netWorkUnable();
            }
        });
        userInfo();
    }

    private void userInfo() {
        RxDataBase.getUser()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<UserDo>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<UserDo>() {
                    @Override
                    public void call(UserDo userDo) {
                        if (GlideLoad.needLoad(true)) {
                            mBitmapTypeRequest
                                    .load(userDo.getUserPhotoUrl())
                                    .placeholder(R.drawable.ic_mine_icon)
                                    .error(R.drawable.ic_mine_icon)
                                    .centerCrop()
                                    .into(new RoundImageViewTarget(img_icon));
                        } else {
                            mBitmapTypeRequest
                                    .load("")
                                    .placeholder(R.drawable.ic_mine_icon)
                                    .error(R.drawable.ic_mine_icon)
                                    .centerCrop()
                                    .into(new RoundImageViewTarget(img_icon));
                        }
                        atv_nickname.setText(TextUtils.isEmpty(userDo.getNickName()) ? "点击设置" : userDo.getNickName());
                        String phone = userDo.getPhone();
                        if (!TextUtils.isEmpty(phone)) {
                            atv_phone.setText(TextUtils.getTrimmedLength(phone) == 11 ?
                                    String.format(Locale.CHINA, "%s%s%s",
                                            phone.substring(0, 3),
                                            "****",
                                            phone.substring(7, 11)) :
                                    phone);
                        }
                    }
                });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_icon:
                showDialog();
                baiduEvent("N1_4_Type", "修改头像");
                break;
            case R.id.rl_nickname:
                startActivityForResult(new Intent(this, SettingsNickNameActivity.class), SET_NICK_NAME);
                baiduEvent("N1_4_Type", "修改昵称");
                break;
            case R.id.rl_password:
                startActivity(new Intent(this, SettingsPassWordActivity.class));
                baiduEvent("N1_4_Type", "修改密码");
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (RESULT_OK == resultCode) {
            switch (requestCode) {
                case SET_NICK_NAME:
                    atv_nickname.setText(data.getStringExtra(ExtraConstant.NICK_NAME));
                    break;
                case SELECT_IMG:
                    final Uri uri = data.getData();
                    if (uri.toString().startsWith("file")) {
                        picturePath = uri.toString().replace("file://", "");
                    } else {
                        String[] filePathColumn = {MediaStore.Images.Media.DATA};
                        ContentResolver cr = getContentResolver();
                        Cursor cursor = cr.query(uri,
                                filePathColumn, null, null, null);
                        if (cursor != null) {
                            cursor.moveToFirst();
                            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                            picturePath = cursor.getString(columnIndex);
                            cursor.close();
                        }
                    }
                    rx(picturePath);
                    break;
                case SELECT_PHOTO:
                    Bundle extras = data.getExtras();
                    Bitmap myBitmap = (Bitmap) extras.get("data");
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    myBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                    String photoData = Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
                    updateUserImgApi.setImg(photoData);
                    updateUserImgApi.startRequest();
                    break;
            }
        }
    }

    private void rx(final String path) {
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                if (!subscriber.isUnsubscribed()) {
                    subscriber.onNext(Bitmap2StrByBase64(ImageUtil.compress(compressDir, picturePath, 200)));
                }
                subscriber.onCompleted();
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<String>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<String>() {
                    @Override
                    public void call(String s) {
                        updateUserImgApi.setImg(s);
                        updateUserImgApi.startRequest();
                    }
                });
    }

    /**
     * 图片转化为byte
     */
    private String Bitmap2StrByBase64(String path) {
        byte[] data = null;
        FileInputStream input = null;
        try {
            input = new FileInputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while ((numBytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
            output.close();
            input.close();
        } catch (FileNotFoundException ex1) {
            ex1.printStackTrace();
        } catch (IOException ex1) {
            ex1.printStackTrace();
        }
        return Base64.encodeToString(data, Base64.DEFAULT);
    }

    /**
     * 显示选择对话框
     */
    private void showDialog() {
        new AlertDialog.Builder(this)
                .setTitle("修改头像")
                .setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        switch (which) {
                            case 0:
                                if (android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.KITKAT) {
                                    Intent selectPhoto = new Intent(Intent.ACTION_GET_CONTENT, null);
                                    selectPhoto.addCategory(Intent.CATEGORY_OPENABLE);
                                    selectPhoto.setType("image/*");
                                    startActivityForResult(selectPhoto, SELECT_IMG);
                                } else {
                                    Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                                    intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
                                    startActivityForResult(intent, SELECT_IMG);
                                }
                                break;
                            case 1:
                                String state = Environment.getExternalStorageState();
                                if (state.equals(Environment.MEDIA_MOUNTED)) {
                                    Intent getImageByCamera = new Intent("android.media.action.IMAGE_CAPTURE");
                                    startActivityForResult(getImageByCamera, SELECT_PHOTO);
                                } else {
                                    snack("没有储存卡");
                                }
                                break;
                            default:
                                break;
                        }
                    }
                })
                .create()
                .show();
    }

    /**
     * 请求用户信息
     */
    private void requestUserInfo() {
        UserInfoApi userInfoApi = new UserInfoApi(MyProfileActivity.class, UserRo.class, new IResponseListener<UserRo>() {
            @Override
            public void onResponse(UserRo userRo) {
                UserDo userDo = userRo.getUserDo();
                if (userRo.getResultNo() == 0 &&
                        userRo.getUserDo() != null) {
                    if (GlideLoad.needLoad(true)) {
                        mBitmapTypeRequest
                                .load(userDo.getUserPhotoUrl())
                                .placeholder(R.drawable.ic_mine_icon)
                                .error(R.drawable.ic_mine_icon)
                                .centerCrop()
                                .into(new RoundImageViewTarget(img_icon));
                    } else {
                        mBitmapTypeRequest
                                .load("")
                                .placeholder(R.drawable.ic_mine_icon)
                                .error(R.drawable.ic_mine_icon)
                                .centerCrop()
                                .into(new RoundImageViewTarget(img_icon));
                    }
                    userSave(userDo);
                }
            }

            @Override
            public void onErrorResponse(VolleyError error) {
                netWorkUnable();
            }
        });
        userInfoApi.startRequest();
    }

    /**
     * 保存用户信息
     */
    private void userSave(UserDo userDo) {
        AppConstant.setUserLogin(this, userDo);
        RxDataBase.saveUser(userDo)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .compose(this.<Boolean>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<Boolean>() {
                    @Override
                    public void call(Boolean aBoolean) {
                        cancelLoadingDialog();
                        EventBus.getDefault().post(new UserOperate(3));
                    }
                });
    }
}
